<!-- 嘎嘎好用了，殡葬上传就用这个 -->
<template>
    <view>
        <uni-forms-item
            :name="name"
            :label="label"
            :required="required"
        >
            <uni-file-picker
            	v-model="myImgArr.photo"
            	file-mediatype="image" 
            	file-extname="png,jpg"
            	limit="2"
            	return-type="array"
            	mode="grid" 
            	@select="select" 
            	@delete="delete1" 
            />
        </uni-forms-item>
    </view>
</template>

<script lang="ts" setup>
    import { onLoad, onShow, onHide, onReady, onUnload } from '@dcloudio/uni-app'
    import { markRaw, onBeforeUnmount, reactive, ref, watchEffect, watch } from 'vue'
    import type { Ref, Raw } from 'vue'
    import uploadApi from '@/apis/uploadApi'
    import { fileUploadBase64ExApi } from '@/apis'
    
    
    
    const props = withDefaults(defineProps<{
        name?: string,
        label?: string,
        modelValue?: string,
        f_id?: string,
        required?: boolean,
        uploadModel?: string,
        uploadName?: string,
        uploadtype?: string,
    }>(), {
        name: '',
        label: '',
        modelValue: '',
        f_id: '',
        uploadModel: '',
        uploadName: '',
        uploadtype: '',
        required: false,
    })
    const emits = defineEmits<{
        (e:'update:modelValue', data: any): void
        (e:'update:f_id', data: any): void
    }>()
    
    const myImgArr: any = reactive({
         photo: [],
         myPhoto: [],   
    })
    watch([() => props.modelValue, () => props.f_id], () => {
        myImgArr['myPhoto'] = []
        if (props.modelValue && props.f_id && props.modelValue.split(',').length == props.f_id.split(',').length) {
            props.modelValue.split(',').forEach((item2: any, index2: number) => {
                myImgArr['myPhoto'].push({
                    // uuid: e.tempFiles[index2].uuid,
                    path: item2,
                    // url: item.imageUrlPrefix + item2,
                    url: 'http://60.191.72.66:10089' + item2, //前面要加路径前缀
                    // name: e.tempFiles[index2].name,
                    // extname: e.tempFiles[index2].extname,
                    index: index2,
                    f_id: props.f_id.split(',')[index2],
                })
            })
            myImgArr['photo'] = JSON.parse(JSON.stringify(myImgArr['myPhoto']))
        }
    }, {
        immediate: true
    })
    
    const fileToBase64 = async(filePath) => {
        const fs = uni.getFileSystemManager();
        try {
            // 读取文件为二进制数据
            const buffer = fs.readFileSync(filePath);
            // 将二进制数据转换为Base64字符串
            const base64 = wx.arrayBufferToBase64(buffer);
            return base64;
        } catch (e) {
            console.error('文件读取或转换错误:', e);
            throw e;
        }
    }
    
    
    const select = async(e) => {
        console.log('选择文件：',e)
        // console.log(e.tempFiles[0].file)
        for(let index = 0; index < e.tempFilePaths.length; index++) {
            console.log('上传文件顺序'+ index)
            let item = e.tempFilePaths[index]
            const base64Data = await fileToBase64(item);
            // console.log('Base64编码:', base64Data);
            // 这里可以使用base64Data进行下一步操作，如设置图片src等
            try {
                let res = await fileUploadBase64ExApi({
                    data: 'data:image/png;base64,' + base64Data,
                    sCode: 'jdzy',
                    model: props.uploadModel,  
                    name: props.uploadName,
                    type: props.uploadtype,
                })
                myImgArr['myPhoto'].push({
                    uuid: e.tempFiles[index].uuid,
                    path: res[0].url,
                    url: 'http://60.191.72.66:10089' + res[0].url,
                    name: e.tempFiles[index].name,
                    extname: e.tempFiles[index].extname,
                    index: index,
                    f_id: res[0].f_id,
                })
            } catch(err) {
                console.log('err')
                myImgArr['photo'] = JSON.parse(JSON.stringify(myImgArr['myPhoto']))
                let myvalue1 = []
                let myvalue2 = []
                myImgArr['myPhoto'].forEach(item => {
                    myvalue1.push(item.path)
                    myvalue2.push(item.f_id)
                })
                emits('update:modelValue', myvalue1.join(','))
                emits('update:f_id', myvalue2.join(','))
                // emits('update:modelValue', '')
            } finally {
                
            }
        }
        let myvalue1 = []
        let myvalue2 = []
        myImgArr['myPhoto'].forEach(item => {
            myvalue1.push(item.path)
            myvalue2.push(item.f_id)
        })
        emits('update:modelValue', myvalue1.join(','))
        emits('update:f_id', myvalue2.join(','))
        myImgArr['photo'] = JSON.parse(JSON.stringify(myImgArr['myPhoto']))
    }
    const delete1 = (e) => {
        console.log('删除：',e)
        console.log(myImgArr['myPhoto'])
        myImgArr['myPhoto'].some((item: any, index: number) => {
            console.log(item)
            console.log(index)
            if (e.tempFile.url == item.url) {
                myImgArr['myPhoto'].splice(index, 1)
                console.log(myImgArr['myPhoto'])
                return true;
            }
        })
        let myvalue1 = []
        let myvalue2 = []
        myImgArr['myPhoto'].forEach((item2, index2) => {
            myvalue1.push(item2.path)
            myvalue2.push(item2.f_id)
        })
        emits('update:modelValue', myvalue1.join(','))
        emits('update:f_id', myvalue2.join(','))
    }
    
</script>

<style>

</style>